<template>
  <div class="admin-layout">
    <AdminHeader />
    <div class="main-wrapper">
      <AdminNavbar />
      <div class="content-wrapper">
        <div class="production-line-dashboard">
          <div class="dashboard-header">
            <h2>mes产线数据</h2>
            <div class="dashboard-actions">
              <el-button type="primary" @click="refreshData">
                <el-icon><Refresh /></el-icon> 刷新数据
              </el-button>
            </div>
          </div>

          <!-- 数据概览卡片 -->
          <div class="data-overview">
            <el-row :gutter="20">
              <el-col :span="6">
                <el-card class="overview-card">
                  <div class="overview-icon running">
                    <el-icon><VideoPlay /></el-icon>
                  </div>
                  <div class="overview-info">
                    <div class="overview-title">运行中生产线</div>
                    <div class="overview-value">{{ statistics.running }}</div>
                  </div>
                </el-card>
              </el-col>
              <el-col :span="6">
                <el-card class="overview-card">
                  <div class="overview-icon stopped">
                    <el-icon><VideoPause /></el-icon>
                  </div>
                  <div class="overview-info">
                    <div class="overview-title">已停止生产线</div>
                    <div class="overview-value">{{ statistics.stopped }}</div>
                  </div>
                </el-card>
              </el-col>
              <el-col :span="6">
                <el-card class="overview-card">
                  <div class="overview-icon completed">
                    <el-icon><Select /></el-icon>
                  </div>
                  <div class="overview-info">
                    <div class="overview-title">已完成生产线</div>
                    <div class="overview-value">{{ statistics.completed }}</div>
                  </div>
                </el-card>
              </el-col>
              <el-col :span="6">
                <el-card class="overview-card">
                  <div class="overview-icon total">
                    <el-icon><DataLine /></el-icon>
                  </div>
                  <div class="overview-info">
                    <div class="overview-title">总生产线数</div>
                    <div class="overview-value">{{ statistics.total }}</div>
                  </div>
                </el-card>
              </el-col>
            </el-row>
          </div>

          <!-- 生产线图表 -->
          <div class="chart-container">
            <el-row :gutter="20">
              <el-col :span="12">
                <el-card class="chart-card">
                  <template #header>
                    <div class="chart-header">
                      <span>生产线状态分布</span>
                    </div>
                  </template>
                  <div class="chart" ref="pieChartRef"></div>
                </el-card>
              </el-col>
              <el-col :span="12">
                <el-card class="chart-card">
                  <template #header>
                    <div class="chart-header">
                      <span>生产效率趋势</span>
                    </div>
                  </template>
                  <div class="chart" ref="historyChartRef"></div>
                </el-card>
              </el-col>
            </el-row>
          </div>

          <!-- 生产线列表 -->
          <div class="production-lines">
            <el-card v-for="line in filteredProductionLines" :key="line.lineId" class="line-card">
              <template #header>
                <div class="line-header">
                  <div class="line-title">
                    <span class="line-id">生产线 #{{ line.lineId }}</span>
                    <el-tag :type="getStatusType(line.status)" effect="dark" class="line-status">
                      {{ line.status }}
                    </el-tag>
                  </div>
                  <div class="line-info">
                    <span><el-icon><Goods /></el-icon> 产品型号: {{ line.productModel }}</span>
                    <span><el-icon><Timer /></el-icon> 开始时间: {{ formatDateTime(line.startTime) }}</span>
                    <span><el-icon><Timer /></el-icon> 结束时间: {{ formatDateTime(line.endTime)||"无" }}</span>
                  </div>
                </div>
              </template>

              <!-- 生产线详情按钮 -->
              <div class="line-actions">
                <el-button type="primary" @click="fetchLineDetail(line.lineId)" size="small">
                  <el-icon><View /></el-icon> {{ expandedLineId === line.lineId ? '收起详情' : '查看详情' }}
                </el-button>
              </div>

              <!-- 工序区列表 (可折叠) -->
              <div v-if="expandedLineId === line.lineId" class="process-tasks">
                <h3>工序区列表</h3>
                <el-divider />
                <el-empty v-if="!currentLineDetail || !currentLineDetail.processTaskList || currentLineDetail.processTaskList.length === 0" description="暂无工序区数据" />
                <div v-else class="task-list">
                  <el-card v-for="task in currentLineDetail.processTaskList" :key="task.taskId" class="task-card" shadow="hover">
                    <div class="task-header">
                      <div class="task-title">
                        <el-icon><Connection /></el-icon>
                        <span>{{ task.processName }}</span>
                        <el-tag :type="getStatusType(task.status)" size="small" effect="plain">{{ taskstatus(task.status) }}</el-tag>
                      </div>
                      <el-button type="primary" size="small" text @click="viewTaskDetails(task)">
                        <el-icon><View /></el-icon> 查看设备
                      </el-button>
                    </div>
                    <div class="task-info">
                      <div class="info-item">
                        <span class="info-label">开始时间:</span>
                        <span class="info-value">{{ formatDateTime(task.startTime) }}</span>
                      </div>
                      <div class="info-item">
                        <span class="info-label">结束时间:</span>
                        <span class="info-value">{{ formatDateTime(task.endTime) || '无' }}</span>
                      </div>
                      <div class="info-item">
                        <span class="info-label">产品型号:</span>
                        <span class="info-value">{{ task.productModel }}</span>
                      </div>
                    </div>
                  </el-card>
                </div>
              </div>
            </el-card>
          </div>
        </div>
      </div>
    </div>

    <!-- 工序区设备详情对话框 -->
    <el-dialog v-model="taskDialogVisible" title="工序区设备详情" width="80%">
      <div v-if="currentTask" class="task-detail">
        <div class="task-info-header">
          <h3>{{ currentTask.processName }} (工序区 #{{ currentTask.taskId }})</h3>
          <el-tag :type="getStatusType(currentTask.status)">{{ currentTask.status }}</el-tag>
        </div>

        <el-descriptions :column="3" border>
          <el-descriptions-item label="所属生产线">{{ currentTask.lineId }}</el-descriptions-item>
          <el-descriptions-item label="产品型号">{{ currentTask.productModel }}</el-descriptions-item>
          <el-descriptions-item label="工序状态">{{ taskstatus(currentTask.status) }}</el-descriptions-item>
          <el-descriptions-item label="开始时间">{{ formatDateTime(currentTask.startTime) }}</el-descriptions-item>
          <el-descriptions-item label="结束时间">{{ formatDateTime(currentTask.endTime) || '无' }}</el-descriptions-item>
          <el-descriptions-item label="创建时间">{{ formatDateTime(currentTask.createdAt) }}</el-descriptions-item>
        </el-descriptions>

        <!-- 设备列表 -->
        <div class="equipment-section">
          <h3>设备列表</h3>
          <el-empty v-if="!currentTask.equipmentList || currentTask.equipmentList.length === 0" description="暂无设备数据" />
          <div v-else class="equipment-grid">
            <el-card v-for="equipment in currentTask.equipmentList" :key="equipment.equipmentId" class="equipment-card" :class="getEquipmentStatusClass(equipment.status)">
              <div class="equipment-header">
                <div class="equipment-title">
                  <el-icon><Cpu /></el-icon>
                  <span>{{ equipment.name }}</span>
                </div>
                <el-tag :type="getEquipmentStatusType(equipment.status)" size="small">{{ equipment.status }}</el-tag>
              </div>
              <div class="equipment-details">
                <div class="detail-item">
                  <span class="detail-label">设备类型:</span>
                  <span class="detail-value">{{ equipment.type }}</span>
                </div>
                <div class="detail-item">
                  <span class="detail-label">当前温度:</span>
                  <span class="detail-value">{{ equipment.currentTemp }}°C</span>
                </div>
                <div class="detail-item">
                  <span class="detail-label">温度阈值:</span>
                  <span class="detail-value">{{ equipment.tempThreshold }}°C</span>
                </div>
                <div class="temp-progress">
                  <el-progress
                    :percentage="getTempPercentage(equipment.currentTemp, equipment.tempThreshold)"
                    :status="getTempStatus(equipment.currentTemp, equipment.tempThreshold)"
                    :stroke-width="10"
                    :format="(percentage) => `${equipment.currentTemp}°C / ${equipment.tempThreshold}°C`"
                  />
                </div>
              </div>
            </el-card>
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
// 导入所需的组件和API
import { ref, computed, onMounted, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import {
    getProductionLines,
    getProductionLineById,
    getRunningProductionLine,
    getFreeProductionLine, processHistoryall, getProcessTaskById
} from '@/api/production'
import * as echarts from 'echarts'
import {
  Refresh, VideoPlay, VideoPause, Select, DataLine, Goods, Timer,
  Cpu, Connection, Box, SetUp, User, View
} from '@element-plus/icons-vue'
import AdminHeader from '@/components/AdminHeader.vue'
import AdminNavbar from '@/components/AdminNavbar.vue'

// 数据定义
const productionLines = ref([]) // 所有生产线列表
const runningProductionLines = ref([]) // 运行中的生产线
const freeProductionLines = ref([]) // 空闲的生产线
const filterStatus = ref('') // 状态筛选
const taskDialogVisible = ref(false) // 工序详情对话框可见性
const currentTask = ref(null) // 当前选中的工序
const expandedLineId = ref(null) // 当前展开的生产线ID
const currentLineDetail = ref(null) // 当前生产线详情

// 图表引用
const pieChartRef = ref(null)
const historyChartRef = ref(null)
let pieChart = null
let historyChart = null

// 过滤后的生产线列表
const filteredProductionLines = computed(() => {
  if (!filterStatus.value) return productionLines.value
  return productionLines.value.filter(line => line.status === filterStatus.value)
})

// 统计数据
const statistics = computed(() => {
  const stats = {
    running: 0,
    stopped: 0,
    completed: 0,
    total: productionLines.value.length
  }

  // 统计不同状态的生产线数量
  productionLines.value.forEach(line => {
    if (line.status === '生产中' || line.status === '加急中') stats.running++
    else if (line.status === '待生产') stats.stopped++
    else if (line.status === '完成') stats.completed++
  })

  return stats
})
// 获取运行中的生产线
const fetchRunningProductionLine = async () => {
  try {
    const res = await getRunningProductionLine()
    if (res.success) {
      runningProductionLines.value = res.data
    }
  } catch (error) {
    ElMessage.error('获取运行中的生产线失败')
  }
}

// 获取空闲的生产线
const fetchFreeProductionLine = async () => {
  try {
    const res = await getFreeProductionLine()
    if (res.success) {
      freeProductionLines.value = res.data
    }
  } catch (error) {
    ElMessage.error('获取空闲生产线失败')
  }
}

// 获取生产线列表
const fetchProductionLines = async () => {
  try {
    const res = await getProductionLines({
      current: 1,
      size: 10
    })
    if (res.success) {
      productionLines.value = res.data.records
      initCharts() // 初始化图表
    }
  } catch (error) {
    ElMessage.error('获取生产线列表失败')
  }
}

// 获取生产线详情
const fetchLineDetail = async (lineId) => {
  try {
    // 如果点击的是已展开的生产线，则收起
    if (expandedLineId.value === lineId) {
      expandedLineId.value = null
      currentLineDetail.value = null
      return
    }

    // 获取生产线详情
    const res = await getProductionLineById(lineId)
    if (res.success) {
      currentLineDetail.value = res.data
      expandedLineId.value = lineId // 设置当前展开的生产线ID
    }
  } catch (error) {
    ElMessage.error('获取生产线详情失败')
  }
}

// 刷新数据
const refreshData = () => {
  fetchProductionLines()
  fetchRunningProductionLine()
  fetchFreeProductionLine()
  // 如果有展开的生产线，刷新其详情
  if (expandedLineId.value) {
    fetchLineDetail(expandedLineId.value)
  }
}

// 查看工序详情
const viewTaskDetails = async (task) => {
    const res = await getProcessTaskById(task.taskId)
  currentTask.value =res.data
  taskDialogVisible.value = true
}

// 格式化日期时间
const formatDateTime = (datetime) => {
  if (!datetime) return ''
  return new Date(datetime).toLocaleString()
}

// 获取状态类型
const getStatusType = (status) => {
  switch (status) {
    case '生产中':
    case '加急中':
      return 'success'
    case '待生产':
      return 'warning'
    case '完成':
      return 'info'
    default:
      return 'warning'
  }
}

// 获取设备状态类型
const getEquipmentStatusType = (status) => {
  switch (status) {
    case '运行':
      return 'success'
    case '维修':
      return 'warning'
    case '停机':
      return 'danger'
    default:
      return 'info'
  }
}

// 获取设备状态样式类
const getEquipmentStatusClass = (status) => {
  switch (status) {
    case '运行':
      return 'equipment-normal'
    case '维修':
      return 'equipment-maintenance'
    case '停机':
      return 'equipment-fault'
    default:
      return ''
  }
}

// 获取温度百分比
const getTempPercentage = (current, threshold) => {
  if (!current || !threshold) return 0
  return Math.min(Math.round((current / threshold) * 100), 100)
}
const taskstatus = (status)=>{
    if (status==="生产中"){
        return "运行中"
    }
    return "未运行"
}
// 获取温度状态
const getTempStatus = (current, threshold) => {
  if (!current || !threshold) return ''
  if (current > threshold * 1.1) return 'exception'
  if (current > threshold) return 'warning'
  return 'success'
}

// 初始化图表
const initCharts = async () => {
    // 初始化饼图 - 生产线状态分布
    if (pieChartRef.value) {
        pieChart = echarts.init(pieChartRef.value)
        const pieOption = {
            tooltip: {
                trigger: 'item',
                formatter: '{a} <br/>{b}: {c} ({d}%)'
            },
            legend: {
                orient: 'vertical',
                left: 10,
                data: ['运行中', '已停止', '已完成']
            },
            series: [
                {
                    name: '生产线状态',
                    type: 'pie',
                    radius: ['50%', '70%'],
                    avoidLabelOverlap: false,
                    label: {
                        show: false,
                        position: 'center'
                    },
                    emphasis: {
                        label: {
                            show: true,
                            fontSize: '18',
                            fontWeight: 'bold'
                        }
                    },
                    labelLine: {
                        show: false
                    },
                    data: [
                        {value: statistics.value.running, name: '运行中', itemStyle: {color: '#67C23A'}},
                        {value: statistics.value.stopped, name: '已停止', itemStyle: {color: '#E6A23C'}},
                        {value: statistics.value.completed, name: '已完成', itemStyle: {color: '#909399'}}
                    ]
                }
            ]
        }
        pieChart.setOption(pieOption)
    }

    // 初始化折线图 - 生产效率趋势
    if (historyChartRef.value) {
    const res = await processHistoryall();
    historyChart = echarts.init(historyChartRef.value);

    // 生成更协调的随机颜色（避免颜色太相近）
    const generateDistinctColor = (index) => {
        const colors = [
            '#c23531', '#2f4554', '#61a0a8', '#d48265',
            '#91c7ae', '#aaaaaa','#561111','#57401f',
            '#00ff2e','#00911C', '#FF00E9','#4F0046',
            '#F5005B','#0930F6', '#013B64','#7200EE',
            '#FF8700','#DCFF00', '#749f83','#FFFFFF',
            '#ca8622', '#bda29a', '#6e7074', '#546570'
        ];
        return colors[index % colors.length] ||
               `hsl(${Math.floor(Math.random() * 360)}, 70%, 50%)`;
    };

    // 按 taskId 分组数据
    const taskGroups = {};
    console.log(res.data);
    res.data.forEach(item => {
        if (!taskGroups[item.taskId]) {
            taskGroups[item.taskId] = [];
        }
        taskGroups[item.taskId].push(item);
    });

    // 提取并格式化日期（显示为MM-DD更简洁）
    const allDates = [...new Set(res.data.map(item => {
        const date = new Date(item.recordTime);
        return `${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`;
    }))].sort((a, b) => new Date(a) - new Date(b));

    // 准备 series 数据
    const series = Object.keys(taskGroups).map((taskId, index) => {
        const groupData = taskGroups[taskId];
        const seriesData = allDates.map(date => {
            // 匹配格式化的日期（MM-DD）
            const record = groupData.find(item => {
                const d = new Date(item.recordTime);
                return `${(d.getMonth()+1).toString().padStart(2, '0')}-${d.getDate().toString().padStart(2, '0')}` === date;
            });
            return record?.yieldRate !== undefined && record?.yieldRate !== null
                ? parseFloat((record.yieldRate * 100).toFixed(2))
                : "未记录"; // 默认值
        });

        return {
            name: `${taskId}号生产线`,
            type: 'line',
            symbol: 'circle',
            symbolSize: 6,
            data: seriesData,
            itemStyle: {
                color: generateDistinctColor(index)
            },
            lineStyle: {
                width: 2
            },
            emphasis: {  // 高亮样式
                itemStyle: {
                    color: generateDistinctColor(index),
                    borderWidth: 2
                }
            }
        };
    });

    const historyOption = {
        tooltip: {
            trigger: 'axis',
            formatter: params => {
                let tip = `日期: ${params[0].axisValueLabel}<br>`;
                params.forEach(param => {
                    tip += `${param.seriesName}: <b>${param.value}%</b><br>`;
                });
                return tip;
            }
        },
        legend: {
            data: Object.keys(taskGroups).map(taskId => `${taskId}号工序区`),
            type: 'scroll',
            top: 0,
            icon: 'roundRect',
            itemWidth: 12,
            itemHeight: 12,
            textStyle: {
                fontSize: 10
            },
            pageIconSize: 8, // 翻页按钮更小
            pageTextStyle: {
                fontSize: 8  // 翻页文字更小
            }
        },
        grid: {
            left: '3%',
            right: '4%',
            bottom: '18%',  // 为图例和dataZoom留空间
            top: '15%',
            containLabel: true
        },
        xAxis: {
            type: 'category',
            boundaryGap: false,
            axisLabel: {
                rotate: 45,  // 日期标签旋转45度防重叠
                fontSize: 10
            },
            data: allDates
        },
        yAxis: {
            type: 'value',
            min: 30,        // 固定Y轴最小值为90%
            max: 100,       // 固定最大值为100%
            axisLabel: {
                formatter: '{value}%'
            },
            splitLine: {
                lineStyle: {
                    type: 'dashed'
                }
            }
        },
        dataZoom: [
            {
                type: 'inside',
                xAxisIndex: 0,
                start: 0,
                end: Math.min(100, 100 * 7 / allDates.length) // 默认显示最近7天
            },
            {
                type: 'slider',
                xAxisIndex: 0,
                height: 20,
                bottom: '8%',
                start: 0,
                end: Math.min(100, 100 * 7 / allDates.length),
                handleStyle: {
                    color: '#2f4554'
                }
            }
        ],
        series: series
    };

    historyChart.setOption(historyOption);

    // 窗口大小变化时自适应
    window.addEventListener('resize', function() {
        historyChart.resize();
    });
}
}

// 窗口大小变化时重绘图表
window.addEventListener('resize', () => {
  pieChart?.resize()
  historyChart?.resize()
})

// 组件挂载时获取数据
onMounted(() => {
  fetchRunningProductionLine()
  fetchFreeProductionLine()
  fetchProductionLines()
})
</script>

<style scoped>
.admin-layout {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background: #f5f7f9;
}

.main-wrapper {
  flex: 1;
  display: flex;
  overflow: hidden;
}

.content-wrapper {
  flex: 1;
  padding: 24px;
  overflow: auto;
  background: #fff;
  margin: 16px;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
}

.production-line-dashboard {
  padding: 20px;
}

.dashboard-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.dashboard-actions {
  display: flex;
  gap: 10px;
}

/* 数据概览卡片样式 */
.data-overview {
  margin-bottom: 20px;
}

.overview-card {
  height: 120px;
  display: flex;
  align-items: center;
  padding: 20px;
}

.overview-icon {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 15px;
}

.overview-icon .el-icon {
  font-size: 30px;
  color: white;
}

.overview-icon.running {
  background-color: #67C23A;
}

.overview-icon.stopped {
  background-color: #E6A23C;
}

.overview-icon.completed {
  background-color: #909399;
}

.overview-icon.total {
  background-color: #409EFF;
}

.overview-info {
  flex: 1;
}

.overview-title {
  font-size: 14px;
  color: #606266;
  margin-bottom: 10px;
}

.overview-value {
  font-size: 24px;
  font-weight: bold;
  color: #303133;
}

/* 图表容器样式 */
.chart-container {
  margin-bottom: 20px;
}

.chart-card {
  margin-bottom: 20px;
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.chart {
  height: 300px;
}

/* 生产线卡片样式 */
.line-card {
  margin-bottom: 20px;
}

.line-header {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.line-title {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.line-id {
  font-size: 18px;
  font-weight: bold;
}

.line-info {
  display: flex;
  gap: 20px;
  color: #606266;
  font-size: 14px;
}

.line-info span {
  display: flex;
  align-items: center;
  gap: 5px;
}

/* 生产线详情按钮 */
.line-actions {
  margin-top: 15px;
  display: flex;
  justify-content: flex-end;
}

/* 工序区列表样式 */
.process-tasks {
  margin-top: 20px;
  padding: 15px;
  background-color: #f9f9f9;
  border-radius: 8px;
}

.task-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 15px;
  margin-top: 15px;
}

.task-card {
  transition: all 0.3s;
}

.task-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
}

.task-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.task-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: bold;
}

.task-info {
  display: flex;
  flex-direction: column;
  gap: 8px;
  font-size: 14px;
  color: #606266;
}

.info-item {
  display: flex;
  align-items: center;
}

.info-label {
  width: 80px;
  color: #909399;
}

/* 工序详情对话框样式 */
.task-detail {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.task-info-header {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 15px;
}

.task-info-header h3 {
  margin: 0;
}

/* 设备列表样式 */
.equipment-section {
  margin-top: 20px;
}

.equipment-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
  gap: 20px;
  margin-top: 15px;
}

.equipment-card {
  border-left: 4px solid #DCDFE6;
  transition: all 0.3s;
}

.equipment-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
}

.equipment-normal {
  border-left-color: #67C23A;
}

.equipment-maintenance {
  border-left-color: #E6A23C;
}

.equipment-fault {
  border-left-color: #F56C6C;
}

.equipment-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.equipment-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: bold;
}

.equipment-details {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.detail-item {
  display: flex;
  align-items: center;
  font-size: 14px;
}

.detail-label {
  width: 80px;
  color: #909399;
}

.detail-value {
  color: #606266;
}

.temp-progress {
  margin-top: 10px;
}
</style>
